<template>
  <div class="container clearfix">
    <div class="filter">
      <h2 class="title">
        筛选查询
      </h2>

      <div class="section">
        <span class="demonstration">核销时间</span>
        <el-date-picker
          v-model="search_form.time"
          type="daterange"
          range-separator="至 "
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </div>
      <div class="section">
        <span class="tip">
          选择医院
        </span>
        <el-select
          v-model="search_form.hospital_id"
          placeholder="请选择"
        >
          <el-option
            v-for="item in hospitalDate"
            :key="item.id"
            :label="item.hospitalName"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">
          回款状态
        </span>
        <el-select
          v-model="search_form.status"
          placeholder="请选择"
        >
          <el-option
            v-for="item in status_arr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">
          订单ID
        </span>
        <div class="content">
          <el-input
            v-model="search_form.orderId"
            placeholder="请输入订单ID"
          />
        </div>
      </div>
      <div class="section">
        <span class="tip">
          未回款总额：{{ totalAmount }}
        </span>
      </div>

      <div class="btn-bar1">
        <el-button
          type="primary"
          siae="small"
          icon="el-icon-search"
          @click="search()"
        >查询结果</el-button>
      </div>
      <div class="btn-bar2">
        <el-button
          type="success"
          siae="small"
          icon="el-icon-search"
          @click="reset()"
        >重置</el-button>
      </div>
    </div>
    <div class="data-table">
      <el-table
        v-loading="table_loading"
        :data="tableData"
        border
        height="660"
        align="center"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="hospitalName"
          align="center"
          label="医院名称"
        />
        <el-table-column
          prop="orderId"
          align="center"
          label="订单ID"
        />
        <el-table-column
          prop="projectName"
          align="center"
          label="项目名称"
        />
        <el-table-column
          prop="payAmount"
          align="center"
          label="线上支付"
        />
        <el-table-column
          prop="verificationDate"
          align="center"
          label="核销时间"
        />
        <el-table-column
          prop="leftAmount"
          align="center"
          label="线下尾款"
        />
        <el-table-column
          prop="whetherUpgrade"
          align="center"
          label="是否升单"
        />
        <el-table-column
          prop="upgradeAmount"
          align="center"
          label="升单金额"
        />
        <el-table-column
          align="center"
          label="消费凭证"
        >
          <template slot-scope="scope">
            <img
              :src="common.img_url+ '/' +scope.row.refundVerify"
              width="100%"
              alt=""
              @click="picturePlay(scope.row)"
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          align="center"
          label="用户姓名"
        />
        <el-table-column
          prop="phone"
          align="center"
          label="用户电话"
        />
        <el-table-column
          prop="needPaidAmount"
          align="center"
          label="需回款金额"
        />
        <el-table-column
          prop="status"
          align="center"
          label="回款状态"
        />
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="220"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === '未回款'"
              type="primary"
              size="small"
              @click="refund_money(scope.row)"
            >完成回款</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <el-button @click="batchOperation()">批量回款</el-button>
      <el-button @click="exports()">导出</el-button>
    </div>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        background
        :page-sizes="[10,20,50,100]"
        :page-size="pageSize"
        :pager-count="11"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @current-change="change_page"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>
<script>
import pagination from '@/components/Pagination'
import axios from '@/utils/request'
import { getHospitalList } from '@/api/hospitalManage'
import { paidBack, paidBackList } from '@/api/finance'
import { downloadPaidBackFile, exportPaidBackFile } from '@/api/file'
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      value1: '',
      value2: '',
      value: true,
      table_loading: false,
      class_arr: [
      ],
      status_arr: [
        {
          value: '',
          label: '全部'
        }, {
          value: '0',
          label: '未回款'
        }, {
          value: '1',
          label: '已回款'
        }
      ],
      total: 0, // 分页总数
      tableData: [],
      hospitalDate: '',
      page: 1,
      pageSize: 10,
      search_form: {
        //   选择医院
        hospital_id: '',
        //   回款状态
        status: '',
        // 时间
        time: '',
        orderId: ''
      },
      showAddMask: false,
      multipleSelection: [],
      // 回款总金额
      totalAmount: 0,
      search_time: [],
      id: '',
      model: 0// 0 初次加载   1表示条件筛选
    }
  },
  //新加路由保存参数
  beforeRouteLeave(to, from, next) {
    // const answer = window.confirm("当前页面搜索条件将会被保存");
    //更新 put
    let keyname = this.$route.name;
    let value = JSON.stringify(this.search_form);
    sessionStorage.setItem(keyname, value);
    next();
  },
  mounted() {
    // 加载列表数据
    if (sessionStorage.getItem(this.$route.name)) {
      this.search_form = JSON.parse(sessionStorage.getItem(this.$route.name));
    }
    this.search()
    // 获取医院列表
    this.get_hospital_list()
  },
  methods: {
    // 筛选
    search() {
      this.model = 1
      this.page = 1
      // 调整时间格式
      if (this.search_form.time !== '') {
        this.search_form.time.forEach((item, index) => {
          var d = new Date(item)

          var yue = d.getMonth() + 1
          var tian = d.getDate()
          if (d.getMonth() < 9) {
            yue = '0' + (d.getMonth() + 1)
          }
          if (d.getDate() < 10) {
            tian = '0' + d.getDate()
          }
          var resDate = d.getFullYear() + '-' + yue + '-' + tian
          this.search_time[index] = resDate
        })
      }
      this.get_list({
        'pageNum': this.page,
        'pageSize': this.pageSize,
        'status': this.search_form.status,
        'hospitalId': (this.search_form.hospital_id).toString(),
        'orderId': this.search_form.orderId,
        'startTime': this.search_time[0] === undefined ? '' : this.search_time[0] + ' 00:00:00',
        'endTime': this.search_time[1] === undefined ? '' : this.search_time[1] + ' 23:59:59'
      })
    },
    // 重置
    reset() {
      this.table_loading = true
      this.$router.go(0)
      this.table_loading = false
    },
    // 获取列表
    get_list(options = {
      'pageNum': this.page,
      'pageSize': this.pageSize
    }) {
      this.table_loading = true
      paidBackList(options).then((result) => {
        const res = result.data
        if (res.code === 0) {
          res.data.responseDTOList.forEach(item => {
            item.whetherVerification = item.whetherVerification === 1 ? '已核销' : '未核销'
            item.whetherUpgrade = item.whetherUpgrade === 1 ? '已升单' : '未升单'
            item.status = item.status === 1 ? '已回款' : '未回款'
          })
          this.totalAmount = res.data.totalAmount
          this.tableData = res.data.responseDTOList
          this.total = res.data.count
          // this.total = Math.ceil(res.data.count / this.pageSize)
          this.table_loading = false
        }
      }).catch((err) => {
        this.table_loading = false
        this.$message.error('服务器网络错误，请稍后重试')
        // this.$message.error(err)
      })
    },
    // 消费凭证展示
    picturePlay(row) {
      this.$router.push({
        path: '/picture_detail',
        query: {
          id: row.orderId
        }
      })
    },

    // 批量汇款操作
    batchOperation() {
      var order_ids = []
      this.multipleSelection.forEach(item => {
        order_ids.push(item.orderId)
      })
      if (order_ids === '') {
        this.$message.error('勾选项至少一个')
      } else {
        this.$confirm('确定批量操作回款？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          paidBack({
            'orderIds': order_ids
          }).then((result) => {
            const res = result.data
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.search()
            } else {
              this.$message.error(res.msg)
            }
          }).catch((err) => {
            this.$message.error('服务器网络错误，请稍后重试')
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }

      // 获取多选框内容
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 导出
    exports(options = {
      'pageNum': this.page,
      'pageSize': this.pageSize,
      'status': this.search_form.status === '' ? null : this.search_form.status,
      'hospitalId': this.search_form.hospital_id,
      'orderId': this.search_form.orderId,
      'startTime': this.search_time[0] === undefined ? '' : this.search_time[0] + ' 00:00:00',
      'endTime': this.search_time[1] === undefined ? '' : this.search_time[1] + ' 23:59:59'
    }) {
      // 调用生成导出文件接口
      exportPaidBackFile(options).then((result) => {
        // 调用下载导出文件接口
        if (result.data.code === 0) {
          downloadPaidBackFile({
            'fileName': result.data.msg
          }, { responseType: 'arraybuffer' }).then((res) => {
            const blob = new Blob([res.data], { type: 'application/x-xlsx' })
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, fileName)
            } else {
              var link = document.createElement('a')
              link.href = window.URL.createObjectURL(blob)
              link.download = result.data.msg
              link.click()
              window.URL.revokeObjectURL(link.href)
            }

            if (res.data.code === 0) {
              this.$message.success(res.data.msg)
            } else {
              this.$message.error(res.data.msg)
            }
          })
        } else {
          this.$message.error(result.data.msg)
        }
      })
    },

    // 完成回款
    refund_money(row) {
      this.$confirm('确定该项目已完成回款？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        paidBack( {
          'orderIds': [row.orderId]
        }).then((result) => {
          const res = result.data
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.search()
          } else {
            this.$message.error(res.msg)
          }
        }).catch((err) => {
          this.$message.error('服务器网络错误，请稍后重试')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },

    // 获取医院列表
    get_hospital_list(){
      getHospitalList( {
        pageNum: this.page,
        pageSize: this.pageSize
      }).then(res => {
        this.hospitalDate = res.data.data.list
      }).catch(res => {
        this.$message.error('网络连接错误，请稍后再试')
      })
    },

    // 分页
    change_page(page) {
      this.page = page
      this.search()
    },

    handleSizeChange(page) {
      this.pageSize = page
      this.page = 1
      this.search()
    }
  }
}
</script>
<style lang="less" scoped>

.container {
  width: 100%;
  height: 100%;
  .filter {
    margin: 20px;
    background-color: #fff;
    box-shadow: 1px 1px 30px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
    padding: 20px;
    position: relative;
    .title {
      font-size: 16px;
    }
    .section {
      display: inline-block;
      vertical-align: middle;
      margin-right: 20px;
      margin-top: 16px;
      .tip {
        font-size: 14px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 5px;
      }
      .content {
        display: inline-block;
        vertical-align: middle;
      }
      .inp {
        display: inline-block;
        vertical-align: middle;
        border: none;
        outline: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 6px;
      }
    }
    .btn-bar1 {
      position: absolute;
      right: 200px;
      top: 10px;
    }
    .btn-bar2 {
      position: absolute;
      right: 80px;
      top: 10px;
    }
  }
  .data-table {
    margin: 20px;
    background-color: #fff;
    box-sizing: border-box;
  }
  .page-controller {
    float: right;
    margin-right: 20px;
  }
}
</style>

